﻿using ShinePipe;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PipeServer
{
    public partial class FrmClient : Form
    {
        ShineNamePipeClient _pipeClient;

        public FrmClient()
        {
            InitializeComponent();
            _pipeClient = new ShineNamePipeClient();
            _pipeClient.ShinePipeDebugEvent += _pipeClient_ShinePipeDebugEvent;
            _pipeClient.ShinePipeRecvEvent += _pipeClient_ShinePipeRecvEvent;
            _pipeClient.ShinePipeCloseEvent += _pipeClient_ShinePipeCloseEvent;
        }

        void _pipeClient_ShinePipeCloseEvent(object sender, ShinePipeCloseEventArgs args)
        {
            this.Invoke(new EventHandler(delegate
            {
                this.btnConnect.Enabled = true;
                this.btnDisconnect.Enabled = false;
                this.btnSend.Enabled = false;
                this.tbxPipeName.Enabled = true;
            }));
        }

        void _pipeClient_ShinePipeDebugEvent(object sender, ShinePipeDebugEventArgs args)
        {
            this.Invoke(new EventHandler(delegate { this.tbxInfo.AppendText(args.Message + "\r\n"); }));    
        }

        void _pipeClient_ShinePipeRecvEvent(object sender, ShinePipeRecvEventArgs args)
        {
            this.Invoke(new EventHandler(delegate { this.tbxRecv.AppendText(args.Message + "\r\n"); }));      
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            bool hasStart =_pipeClient.Start(this.tbxPipeName.Text.Trim());

            this.btnConnect.Enabled =!hasStart;
            this.btnDisconnect.Enabled = hasStart;
            this.btnSend.Enabled = hasStart;
            this.tbxPipeName.Enabled = !hasStart;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            _pipeClient.Write(this.tbxSend.Text.Trim());
        }

        private void FrmClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            _pipeClient.Stop();
        }

        private void FrmClient_Load(object sender, EventArgs e)
        {

        }
    }
}
